package com.tianji.learning.listener;

import cn.hutool.json.JSONUtil;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.dto.LikedTimesDTO;
import com.tianji.learning.domain.entity.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ReplyLikedListener {
    @Autowired
    private IInteractionReplyService replyService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = MqConstants.Queue.QA_LIKED_TIMES_QUEUE,durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.LIKE_RECORD_EXCHANGE,type = ExchangeTypes.TOPIC),
            key =MqConstants.Key.QA_LIKED_TIMES_KEY))
    public void onReplyLiked( List<LikedTimesDTO> dtos){
        /*if (dto.getLikedTimes()<=0){
            dto.setLikedTimes(0);
        }
        log.debug("监听到回答或评论{}的点赞数变更:{}", dto.getBizId(), dto.getLikedTimes());
        replyService.lambdaUpdate().set(InteractionReply::getLikedTimes,dto.getLikedTimes())
                .eq(InteractionReply::getId,dto.getBizId())
                .update();*/
        List<InteractionReply> replies=new ArrayList<>();
        log.debug("监听到回答或评论的点赞数变更:{},", JSONUtil.toJsonStr(dtos));
        for (LikedTimesDTO dto : dtos) {
            InteractionReply interactionReply = new InteractionReply();
            interactionReply.setId(dto.getBizId());
            interactionReply.setLikedTimes(dto.getLikedTimes());
            interactionReply.setUpdateTime(LocalDateTime.now());
            replies.add(interactionReply);
        }
        replyService.updateBatchById(replies);
    }
}
